from flask import Flask, request, jsonify
import oss2

app = Flask(__name__)

# 阿里云 OSS 认证信息
auth = oss2.Auth('LTAI5tSSsZreQros8dcchrTe', 'dKoToq83nsV1xMTJN9VwIiryzKOkhg')

# 设置 Endpoint 和 Bucket 信息
endpoint = "https://oss-cn-beijing.aliyuncs.com"
bucketName = "mjseed-code-image"
bucket = oss2.Bucket(auth, endpoint, bucketName)


# 1. 创建（上传文件）
@app.route('/upload', methods=['POST'])
def upload_file():
    try:
        file = request.files.get('file')
        if not file:
            return jsonify({'error': '未找到文件'}), 400

        # 获取文件名
        filename = file.filename

        # 上传文件到 OSS
        bucket.put_object(filename, file)

        return jsonify({'message': '上传成功', 'filename': filename})

    except Exception as e:
        return jsonify({'error': str(e)}), 500


# 2. 删除文件
@app.route('/delete/<filename>', methods=['DELETE'])
def delete_file(filename):
    try:
        # 删除 OSS 中的文件
        bucket.delete_object(filename)
        return jsonify({'message': '删除成功', 'filename': filename})

    except Exception as e:
        return jsonify({'error': str(e)}), 500


# 3. 更新文件（先删除旧文件，再上传新文件）
@app.route('/update/<filename>', methods=['PUT'])
def update_file(filename):
    try:
        # 获取新文件
        new_file = request.files.get('file')
        if not new_file:
            return jsonify({'error': '未找到新文件'}), 400

        # 删除旧文件
        bucket.delete_object(filename)

        # 上传新文件
        bucket.put_object(filename, new_file)

        return jsonify({'message': '更新成功', 'filename': filename})

    except Exception as e:
        return jsonify({'error': str(e)}), 500


# 4. 查询文件列表
@app.route('/list', methods=['GET'])
def list_files():
    try:
        # 获取 OSS 中的文件列表
        # list_objects 返回一个分页结果，这里只获取前100个文件
        result = bucket.list_objects()
        files = [item.key for item in result.object_list]
        return jsonify({'files': files})

    except Exception as e:
        return jsonify({'error': str(e)}), 500


if __name__ == '__main__':
    app.run(debug=True)